<?php

namespace App\Services;

use App\Exceptions\InvalidRequestException;
use DeviceDetector\Parser\Client\Browser;
use Endroid\QrCode\QrCode;
use hisorange\BrowserDetect\Exceptions\Exception;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Routing\Controller;
use Yansongda\Pay\Pay;
use Yansongda\Pay\Log;

class PayService
{
    public function checkParams($order)
    {
        //循环数组，key是否存在,不存则抛出错误
        foreach (['sn', 'price', 'subject'] as $key) {
            if (!key_exists($key, $order)) {
                throw new InvalidRequestException("支付宝参数[{$key}]不存在");
            }
        }
    }

    public function alipay(array $order, $action = 'web')
    {
        //验证必要参数
        $this->checkParams($order);
        //定义key配置符合框架key命名规范
        $order['out_trade_no'] = $order['sn'];
        $order['total_amount'] = $order['price'];

        $alipay = Pay::alipay($this->alipayConfig())->$action($order);

        return $alipay->send();// laravel 框架中请直接 `return $alipay`
    }

    public function alipayConfig()
    {
        $config = config('site.alipay');

        //配置项中增加回调的路由地址和通知的路由地址，通过对应的地址来转入后台对应的控制器中
        $config['return_url'] = route('common.alipay.sync', module()['id']);
        $config['notify_url'] = route('common.alipay.async', module()['id']);

        if ($config['mode'] != 'dev') {
            unset($config['mode']);
        };

        return $config;
    }

    public function wepayConfig()
    {
        $config = config('site.wepay');

        //配置项中增加回调的路由地址和通知的路由地址，通过对应的地址来转入后台对应的控制器中

        $config['notify_url'] = route('common.wepay.async', module()['id']);
        if ($config['mode'] != 'dev') {
            unset($config['mode']);
        };

        return $config;
    }
    public function wepay($order,$action='scan'){
        $method='wepay'.ucfirst($action);
        $this->$method($order);
    }
    public function wepayScan(array $order)
    {
        //验证必要参数
        $this->checkParams($order);
        //获取微信二维码扫描的图片地址
        $result = Pay::wechat($this->wepayConfig())->scan(
            [
                'out_trade_no' => $order['sn'],
                'total_free' => $order['price'] * 100,
                'body' => $order['subject'],
            ]
        );
//        微信没有企业账号暂时只测试二维码

//        $result['code_url'] = 'https://www.51fd111.com/'; //暂时固定网址

        $qrCode = new QrCode($result['code_url']);
        header('Content-Type: ' . $qrCode->getContentType());
        echo $qrCode->writeString();
        die;
    }

    public function wepayWap(array $order)
    {
        $this->checkParams($order);
        return Pay::wechat($this->wepayConfig())->wap(
            [

                'out_trade_no' => $order['sn'],
                'total_free' => $order['price'] * 100,
                'body' => $order['subject'],

            ])->send();
    }

}
